package com.credithc.scs.webservice.impl;

import com.alibaba.fastjson.JSONObject;
import com.credithc.scs.webservice.SignService;
import com.credithc.signature.common.ro.OldSignProviderReq;
import com.credithc.signature.common.service.SealInfoService;
import com.credithc.signature.common.utils.UUIDUtil;
import com.credithc.signature.facade.constant.Constant;
import com.credithc.signature.facade.facadeenum.ResponseEnum;
import com.credithc.signature.facade.service.ParamVerifyService;
import com.credithc.signature.facade.service.RestSignService;
import com.credithc.signature.facade.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jws.WebService;
import java.util.List;

/**
 * 老签章接口webservice实现<br/>
 * 作者：sunyang
 * 创建：2019/5/23 16:10
 * 版本：v1.0.0<br/>
 */
@Slf4j
@WebService(serviceName = "SignService", targetNamespace = "http://webservice.scs.credithc.com/",
        endpointInterface = "com.credithc.scs.webservice.SignService")
public class SignServiceImpl implements SignService {

    @Autowired
    private RestSignService restSignService;

    @Autowired
    ParamVerifyService paramVerifyService;

    @Autowired
    private SealInfoService sealInfoService;

    /**
     * @param channelId   String 渠道
     * @param templateId  String 模板Id
     * @param jsonBody    String json数据
     * @param callBackUrl String 回调url地址
     * @throws Exception
     */
    @Override
    public String signContract(String channelId, String templateId, int isSeal, String jsonBody, String callBackUrl) throws Exception {

        final String signatureSN = UUIDUtil.getUUID();

        MDC.put(Constant.MDC_REQUEST_SN, signatureSN);
        try {
            // 1、校验渠道
            if (!paramVerifyService.existChannel(channelId)) {
                return ResponseUtil.getResponseMessage(ResponseEnum.ILLEGAL_CHANNEL.getCode());
            }

            // 2、校验模板
            if (!paramVerifyService.existTemplate(templateId, channelId)) {
                return ResponseUtil.getResponseMessage(ResponseEnum.ILLEGAL_TEMPLATE.getCode());
            }

            //3、校验公章
            OldSignProviderReq oldSignProviderReq = JSONObject.parseObject(jsonBody, OldSignProviderReq.class);
            List<String> officialSeals = oldSignProviderReq.getOfficialSealsCodes();
            if (!paramVerifyService.existSeal(officialSeals, channelId, templateId, isSeal)) {
                return ResponseUtil.getResponseMessage(ResponseEnum.ILLEGAL_OFFICIAL_SEAL.getCode());
            }
            return restSignService.signature(channelId, templateId, isSeal, jsonBody, callBackUrl, signatureSN);
        } finally {
            try {
                MDC.remove(Constant.MDC_REQUEST_SN);
            } catch (Exception e) {
                // 不做处理
            }
        }
    }
}
